<?php

/**
 * TwitterCommand class
 *
 * @author Julot <andy.julot@gmail.com>
 * @since Monday, July 18, 2011. 09:12 AM
 */
class TwitterCommand extends CConsoleCommand {

	public function getHelp() {
		return <<<EOD
USAGE
    twitter [test]
DESCRIPTION
    This command will retrieve twitter home\'s timeline.
EOD;
	}

	public function run($args) {
		echo "Retrieving twitter friend's timeline started.\n";
		if ($args && $args[0] == 'test') {
			$this->_test();
		} else {
			$this->_retrieve();
		}
	}

	protected function _retrieveFriendTimeline($sinceId=null) {
		$params = Yii::app()->params['twitter'];
		$username = $params['username'];
		$password = $params['password'];
		$consumerKey = $params['consumer']['key'];
		$consumerSecret = $params['consumer']['secret'];
		$twitter = new Twitter($consumerKey, $consumerSecret);
		$twitter->setOAuthToken($params['access']['token']['value']);
		$twitter->setOAuthTokenSecret($params['access']['token']['secret']);
		$responses = $twitter->statusesHomeTimeline(null, $sinceId);
		$friends = array();
		foreach ($responses as $response) {
			if (in_array($response['user']['id'], $params['friends'])) {
				if (!preg_match("/@|(cont)|http/i", $response['text'])) {
					$friends[] = $response;
				}
			}
		}
		return $friends;
	}

	protected function _test() {
		echo "!!! TEST MODE !!!\n";

		$timelines = $this->_retrieveFriendTimeline();
		echo "Found " . count($timelines) . " new timeline(s).\n\n";
		foreach ($timelines as $key=>$timeline) {
			echo $key;
			echo ": ";
			echo $timeline['user']['name'] . ' @ ' . $timeline['created_at'];
			echo "\n";
			echo $timeline['text'];
			echo "\n";
		}
	}

	protected function _retrieve() {
		Yii::log(
			'Retrieving twitter friend\'s timeline.',
			"info",
			'application.commands.TwitterCommand'
		);
		$twitter = News::TYPE_TWITTER;
		$ref = Reference::model()->find('name=:name', array(':name'=>$twitter));
		if ($ref) {
			$json = CJSON::decode($ref->value, true);
			$sinceId = $json['lastId'];
		} else {
			$ref = new Reference;
			$ref->name = $twitter;
			$sinceId = null;
		}
		$timelines = $this->_retrieveFriendTimeline($sinceId);
		echo "Found " . count($timelines) . " new timeline(s).\n\n";
		foreach ($timelines as $i=>$timeline) {
			if ($i == 0) {
				$id = $timeline['id'];
				$ref->value = '{"lastId": "' . $id . '"}';
				$ref->save();
			}
			$model = new NtmcNews;
			$model->sender = $timeline['user']['name'];
			$model->dateTime = time();
			$model->contact = $timeline['user']['id'];
			$model->value = $timeline['text'];
			$n = $i + 1;
			echo "Saving timeline #$n to news... ";
			if ($model->save()) {
				echo "OK ^_^v\n";
				// We must set notified here because notified will be
				// automatically set to flase before save for new record.
				$model->notified = 1;
				$model->save();
			}
			else echo "Error >_<\n";
//			echo "Sending mail notification #$i... ";
//			if ($model->sendNotification()) echo "OK ^_^v\n";
//			else echo "Error >_<\n";
		}
	}

}
